package com.gmail.avenderov.list;

/**
 * Stack implementation that uses linked list to store the data.
 */
public class ListBasedStack<T> implements Stack<T> {

    private Node<T> head;
    
    @Override
    public boolean isEmpty() {
        return head == null;
    }

    @Override
    public int getSize() {
        int length = 0;
        if (!isEmpty()) {
            Node<T> currentNode = head;
            do {
                length++;
                currentNode = currentNode.getNext();
            } while (currentNode != null);
        }
        return length;    
    }

    @Override
    public T pop() {
        T value = null;
        if (!isEmpty()) {
            value = head.getValue();
            head = head.getNext();
        }
        return value;
    }

    @Override
    public void push(T value) {
        if (value == null) {
            throw new NullPointerException("Can't push null into stack");
        }
        Node<T> currentNode = new NodeImpl<T>(value);
        if (!isEmpty()) {
            currentNode.setNext(head);
        }
        head = currentNode;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder(this.getClass().getSimpleName() + "{");
        if (!isEmpty()) {
            Node<T> currentNode = head;
            do {
                result.append(currentNode.getValue());
                currentNode = currentNode.getNext();
                if (currentNode != null) {
                    result.append(", ");
                }
            } while (currentNode != null);
        }
        result.append("}");
        return result.toString();
    } 
    
}
